package com.aabte.spring.annotation.config;

import com.aabte.spring.beanpostprocess.MyBeanPostProcessor;
import com.aabte.spring.beans.Car;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.BeanValidationPostProcessor;

/**
 * 自定义容器管理Bean的生命周期
 * 1、指定初始化和销毁方法（init-method/destroy-method），通过@Bean注解参数指定初始化和销毁方法名称
 *      初始化方法在Bean实例化并且属性赋值后被调用
 *      销毁方法在容器关闭时被调用
 * 2、实现InitializingBean接口，实现初始化逻辑；实现DisposableBean接口，实现销毁逻辑。
 * 3、使用JSR250规定的注解：使用@PostConstant注解标注在初始化方法上，使用@PreDestroy注解标注在销毁方法上
 * 4、使用BeanPostProcessor（Bean的后置处理器），每个Bean都会被调用到，内置的Bean也会被执行
 *
 * @PostConstant和@PreDestroy注解初始化方法的执行请看
 * @see InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization(Object, String)
 *
 * 初始化方法执行顺序：
 *      Constructor
 *      BeanPostProcessor.postProcessBeforeInitialization
 *      @PostConstant
 *      InitializingBean.afterPropertiesSet
 *      @Bean(initMethod = "init")
 *      BeanPostProcessor.postProcessAfterInitialization
 *
 * 比较重要的几个BeanPostProcessor实现：
 * {@link InitDestroyAnnotationBeanPostProcessor}
 * {@link BeanValidationPostProcessor}
 * {@link AutowiredAnnotationBeanPostProcessor}
 *
 * @author Daniel
 */
@Configuration
public class LifeCycleConfig {

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public Car car() {
        return new Car();
    }

    @Bean
    public BeanPostProcessor myBeanPostProcessor() {
        return new MyBeanPostProcessor();
    }

}
